#define _CRT_SECURE_NO_WARNINGS 1
#include "Tree.h"
BTNode* TreeBuyNode(BTDateType index)
{
	BTNode* buynode = (BTNode*)malloc(sizeof(BTNode));
	if (buynode == NULL)
	{
		perror("malloc error!");
		exit(1);
	}
	buynode->value = index;
	buynode->left = NULL;
	buynode->right = NULL;
	return buynode;
}
void TreePreOrder(BTNode* tree)
{
	if (tree == NULL)
		return;
	printf("%d ", tree->value);
	TreePreOrder(tree->left);
	TreePreOrder(tree->right);
}
void TreeInorder(BTNode* tree)
{
	if (tree == NULL)
		return;
	TreeInorder(tree->left);
	printf("%d ", tree->value);
	TreeInorder(tree->right);
}
void TreePostorder(BTNode* tree)
{
	if (tree == NULL)
		return;
	TreePostorder(tree->left);
	TreePostorder(tree->right);
	printf("%d ", tree->value);
}
int TreeNodeNumber(BTNode* tree)
{
	if (tree == NULL)
		return 0;
	return 1 + TreeNodeNumber(tree->left) + TreeNodeNumber(tree->right);
}
int TreeDepth(BTNode* tree)
{
	if (tree == NULL)
		return 0;
	int Binleft = TreeDepth(tree->left);
	int Binright = TreeDepth(tree->right);
	return Binleft > Binright ? Binleft + 1 : Binright + 1;
}
int TreeLeafNode(BTNode* tree)
{
	if (tree == NULL)
		return 0;
	if (tree->left == NULL && tree->right == NULL)
		return 1;
	return TreeLeafNode(tree->left) + TreeLeafNode(tree->right);
}
int TreeKNums(BTNode* tree, int k)
{
	if (tree == NULL)
		return 0;
	if (k == 1)
		return 1;
	return TreeKNums(tree->left, k-1) + TreeKNums(tree->right, k-1);
}
BTNode* TreeFind(BTNode* tree, BTDateType x)
{
	if (tree == NULL)
		return NULL;
	if (tree->value == x)
		return tree;
	BTNode* findleft = TreeFind(tree->left, x);
	if (findleft) return findleft;
	BTNode* findright = TreeFind(tree->right, x);
	if (findright) return findright;
	return NULL;
}
void TreeDestroy(BTNode* tree)
{
	if (tree == NULL)
		return;
	TreeDestroy(tree->left);
	TreeDestroy(tree->right);
	free(tree);
	tree = NULL;
}
void TreeLevelTraversal(BTNode* tree)
{
	assert(tree);
	Queue q;
	QueueInit(&q);
	QueuePush(&q,tree);
	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		QueuePop(&q);
		printf("%d ", front->value);
		if(front->left)
			QueuePush(&q, front->left);
		if(front->right)
			QueuePush(&q, front->right);
	}
}
bool IsCompleteBinaryTree(BTNode* tree)
{
	assert(tree);
	Queue q;
	QueueInit(&q);
	QueuePush(&q,tree);
	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		QueuePop(&q);
		if (front == NULL)
			break;
		QueuePush(&q, front->left);
		QueuePush(&q, front->right);
	}
	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		QueuePop(&q);
		if (front != NULL)
		{
			QueueDestroy(&q);
			return false;
		}
	} 
	QueueDestroy(&q);
	return true;
}
